//
//  JPUSH.m
//  MDC
//
//  Created by 123456 on 16/8/26.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "JPUSH.h"
//#import "ReflectUtil.h"
#import "GUAAlertView.h"
#import "JPUSHService.h"
#import "GetiPhoneDevice.h"
#import "MoreViewController.h"


@interface JPUSH()
{
    UIAlertController  *DSDK_alertController;
    GUAAlertView *v; //自定义弹出框
}

@end



@implementation JPUSH
singleton_for_implementation(JPUSH)

- (void)registerPushServiceWithApplication:(UIApplication *)app :(NSDictionary *)launch {
    //ALBBSDK
    [self registerMsgReceive]; //收到的推送消息
    
    [self registerAPNS:app withDictionary:launch];
    
   // [JPUSHService setDebugMode];
    [JPUSHService crashLogON];
}

#pragma mark -  推送的业务逻辑处理（跳转到指定页面）、判断方法 没有内推的情况下。配合本地通知、信息通知使用。
/*
- (void)callMethodPuchApplication:(nonnull UIApplication*)application receiveRemoteNot:(nonnull NSDictionary*)userInfo enclosureInfo:(void (^ _Nullable)(id _Nullable))info  {
    NSString *alertStr = [userInfo[@"aps"] objectForKey:@"alert"]; //推送的正文
    NSString *badgeStr = [[userInfo objectForKey:@"aps"] objectForKey:@"badge"];;  // 信息条数
    
    //    [CloudPushSDK handleLaunching:launchOptions]; // 作为 apns 消息统计
    [JPUSHService setBadge:[badgeStr integerValue]+1];
    [self updateApplicationIconBadgeNumber];
    
    
    [application setApplicationIconBadgeNumber:[badgeStr integerValue]];
    [NSUD setObject:userInfo forKey:MDC_USER_INFO_DIC]; //保存推送内容
    
    NSLog(@"%@--->%@",alertStr,badgeStr);
    // 前台 或者
    NSLog(@"打印APP 状态--》 %ld",(long)[UIApplication sharedApplication].applicationState);
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive || application.applicationState == UIApplicationStateBackground) {
        // 构建本地推送 （前台行为处理）
        UILocalNotification * localNotification = [[UILocalNotification alloc] init];
        localNotification.userInfo = userInfo;
        localNotification.soundName = UILocalNotificationDefaultSoundName;//@"SStext.wav"; //
        // localNotification.alertBody = userInfo[@"aps"][@"alert"];
        localNotification.fireDate = [NSDate date];
        [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; //构建了本地通知会跳转到本地通知方法
        info(@"1");
    }else {
        // 后台直接跳转到指定页面
        TabBarC *tabbarCont = (TabBarC *)application.keyWindow.rootViewController;  //self.window.rootViewController;
        NavigationC *navigationCont = (NavigationC *)tabbarCont.viewControllers[0];
        if(navigationCont.viewControllers.count > 1) {
            [navigationCont popToRootViewControllerAnimated:YES];
        }
        
        if (![navigationCont.tabBarController.selectedViewController isEqual:navigationCont]) {
            navigationCont.tabBarController.selectedIndex = 0;
        }
        
        NSLog(@"%@--->%@",navigationCont.viewControllers,userInfo);
        SearchVC * search = navigationCont.viewControllers[0];
        [search JumpWithVlue:userInfo];
        
    }

}

*/

#pragma mark - 注册推送
- (void)registerAPNS:(UIApplication *)application withDictionary:(NSDictionary *)launchOptions {
    //============================注册极光推送=================================
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories 必须为nil
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound |UIRemoteNotificationTypeAlert)categories:nil];
    }
    
    
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:nil];

    
//    [CloudPushSDK handleLaunching:launchOptions]; // 作为 apns 消息统计
//    [[UIApplication sharedApplication] cancelAllLocalNotifications]; // 清除全部通知。
//    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; //角标清0

}


#pragma mark - 注册通道监听
- (void) registerMsgReceive {
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidLogin:) name:kJPFNetworkDidLoginNotification object:nil];
    NSLog(@"推送通道监听建立成功!");
}

#pragma mark - 推送下来的消息抵达的处理示例
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * dic = [notification userInfo];
    NSString *content = [dic valueForKey:@"content"];
    NSDictionary *extras = [dic valueForKey:@"extras"];
    NSString *customizeField1 = [extras valueForKey:@"device_id"]; //服务端传递的Extras附加字段，key是自己定义的
    
    NSLog(@"推送消息============ %@",content);
    NSLog(@"推送消息附加字段============ %@",customizeField1);

    // 报警提示
    if(![NSThread isMainThread])
    {
//        dispatch_async(dispatch_get_main_queue(), ^{ //防止在非主线程加载
            if (dic != nil) {
                // 如果是罩，就不给推送
                NSLog(@"----->打印:%@--->%d",[NSUD objectForKey:MDC_SET_MASKVIEW],[[NSUD objectForKey:MDC_SET_MASKDATAVIEW] intValue]);
                
                [self pushDidReceiveMessage:dic extrasdic:extras];
            }
//        });
    } else {
        [self pushDidReceiveMessage:dic extrasdic:extras];
    }
}
- (void)pushDidReceiveMessage:(NSDictionary *)dictionary extrasdic:(NSDictionary *)extrasdict {
       NSString *content = [dictionary valueForKey:@"content"];
        // 如果是罩，就不给推送
        NSLog(@"----->打印:%@--->%d",[NSUD objectForKey:MDC_SET_MASKVIEW],[[NSUD objectForKey:MDC_SET_MASKDATAVIEW] intValue]);
        
        if (![[NSUD objectForKey:MDC_SET_MASKVIEW] isEqualToString:@"加遮"]) {
            if ([[NSUD objectForKey:MDC_SET_MASKDATAVIEW] intValue] == 0) {
                if (self.sonWindow != nil && self.tabBarC != nil) {
                    [self.searchVC addUnreadCount:extrasdict];                  //-- 这里需要的功能是动态添加Cell 的小红点，
                    [self updateApplicationIconBadgeNumber];
                    if ([dictionary objectForKey:@"content"] != nil) {
                        
                        if ([extrasdict objectForKey:@"type"] != nil) {
                            if (![[NSUD objectForKey:MDC_CLOSE_SCANNING] isEqualToString:@""]) {
                                NSLog(@"----->%@",[NSUD objectForKey:MDC_CLOSE_SCANNING]);
                                 [[NSNotificationCenter defaultCenter] postNotificationName:[NSUD objectForKey:MDC_CLOSE_SCANNING] object:self userInfo:nil];
                            }
                             [self abnormalExit:[extrasdict objectForKey:@"type"]];
                        }
                        
                        [v removeFromSuperview];
                         v = [GUAAlertView alertViewWithTitle:@"通知" message:content buttonTitle:@"确定"buttonTouchedAction:^{
                            NSLog(@"button touched");
                            
                             if ([extrasdict objectForKey:@"type"] == nil) {
                                 if (self.navigationC.viewControllers.count > 0) {
                                     [self.navigationC popToRootViewControllerAnimated:YES];
                                 }
                                 
                                 if (self.navigationC.tabBarController.selectedIndex == 1) {
                                     self.navigationC.tabBarController.selectedIndex = 0;
                                 }
                                 
                                 NSLog(@"%@--->%@",self.navigationC.viewControllers, dictionary);
                                 [self.searchVC JumpWithVlue:extrasdict];
                                 UIWindow *window = [UIApplication sharedApplication].keyWindow;
                                 [window.superview removeFromSuperview];
                             }
                             
                             
                        } dismissAction:^{
                            NSLog(@"dismiss");
                        }];
                        [v show];
                        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    
                    }
                    
                }

            }
        }
}


- (void)networkDidLogin:(NSNotification *)notification {
    NSLog(@"已登录");
    if (![[GetiPhoneDevice getCurrentDeviceModel] isEqualToString:@"iPhone Simulator"]) {
        //获取登陆ID
        if ([JPUSHService registrationID]) {
            NSString * registrationStr  = [JPUSHService registrationID];
            [NSUD setObject:registrationStr forKey:MDC_REGISTRATION_ID];
            NSLog(@"get RegistrationID: %@",registrationStr);
        }

     }
}
- (void)abnormalExit:(NSString *)str {
    if ([str isEqualToString:@"服务器重启"]) { //服务器错误
          [MoreViewController logout:self.sonWindow.rootViewController];
    }else { //逼出
          [MoreViewController moreAbnormalExit:self.sonWindow.rootViewController];
    }
    
}


//添加推送别名
- (void)albbBindChannel {
    NSString *bindStr= @"";
    NSString *strFrom4 = @"";
    
    NSString *registrationStrFrom4  = [NSUD objectForKey:MDC_REGISTRATION_ID];
   
    if (registrationStrFrom4 == nil) {
        return;
    }else {
        if ([registrationStrFrom4 isEqualToString:@"异常登记ID"]) {
          strFrom4 = @"abcd";
        }else {
          strFrom4 = registrationStrFrom4 != nil ? [registrationStrFrom4 substringFromIndex:registrationStrFrom4.length - 4] : @"";
        }
    }
    
    
  
    if (![IP isEqualToString:@"http://120.25.159.212"]) {
        bindStr = [NSString stringWithFormat:@"test_%@%@",MDC_USERCODE,strFrom4];
    }else {
        bindStr = [NSString stringWithFormat:@"formal_%@%@",MDC_USERCODE,strFrom4];
    }
    NSLog(@"打印绑定账号：%@",bindStr);

    if (MDC_USERCODE != nil && ![MDC_USERCODE isEqualToString:@" "]) {
        
        [JPUSHService setTags:nil aliasInbackground:bindStr];
        
    }else {
        NSLog(@"打印绑定的空账号：%@",MDC_USERCODE);
    }
}

//删除推送别名
- (void)Deleteaccount{
    [JPUSHService setTags:nil aliasInbackground:@""];
}

// 更新未读小红点
- (void)updateApplicationIconBadgeNumber {
    NSInteger iconBadge  = [UIApplication sharedApplication].applicationIconBadgeNumber;
    [NSUD setObject:[NSNumber numberWithInteger:iconBadge] forKey:@"applicationIconBadgeNumber"];
    
    int numberBadge = [[NSUD objectForKey:@"applicationIconBadgeNumber"] intValue];
    [UIApplication sharedApplication].applicationIconBadgeNumber = numberBadge;
    [NSUD setObject:@(numberBadge) forKey:@"applicationIconBadgeNumber"];
}

#pragma mark - 设置 访问密匙 对取出的cookie进行反归档处理
- (void)updateSession{
    NSArray *cookies =[NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"allCookie"]];
    if (cookies){
        NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        for (id cookie in cookies ){
            [cookieStorage setCookie:(NSHTTPCookie *)cookie]; //把保存在本地的Cookie 设置进去
            NSLog(@"比较后-AppDelegate这打印：--->%@",[(NSHTTPCookie *)cookie valueForKey:@"value"]);
        }
    }
}


// ???： -----初始化属性 -- 这里崩溃过一次！
- (NavigationC *)navigationC {
    return  _navigationC =  (NavigationC *)self.tabBarC.viewControllers[0];
}
- (SearchVC *)searchVC {
    _searchVC = (SearchVC *)self.navigationC.viewControllers[0];
    return _searchVC;
}

@end
